package com.example.tobebigfe.jsbridge

import android.os.Bundle
import android.util.Log
import android.webkit.JavascriptInterface
import android.webkit.WebSettings.LOAD_NO_CACHE
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.tobebigfe.R
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONObject

// 提取一个通用的WebActivity
abstract class WebActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        WebView.setWebContentsDebuggingEnabled(true)
        webView.settings.javaScriptEnabled = true
        webView.settings.cacheMode = LOAD_NO_CACHE
        webView.webViewClient = WebViewClient()

        // 在加载网页前添加我们的js对象
        webView.addJavascriptInterface(BridgeObject(webView), "androidBridge")

        // 加载assets中的网页
        webView.loadUrl(getLoadUrl())
    }

    // 提出一个抽象方法，让子类实现加载的url
    abstract fun getLoadUrl(): String

    interface BridgeModule {
        fun callFunc(func: String, arg: JSONObject)
    }

    inner class BridgeObject(val webView: WebView) {

        private val bridgeModuleMap = mutableMapOf<String, BridgeModule>()

        init {
            bridgeModuleMap["UI"] = JSBridgeUI()
        }

        @JavascriptInterface
        fun callNative(callbackId: String, method: String, arg: String) {
            Log.e("WebView", "callNative ok. args is $arg")
            val jsonArg = JSONObject(arg)
            val split = method.split(".")
            val moduleName = split[0]
            val funcName = split[1]

            val module = bridgeModuleMap[moduleName]
            module?.callFunc(funcName, jsonArg)
        }
    }

    inner class JSBridgeUI : BridgeModule {

        override fun callFunc(func: String, arg: JSONObject) {
            when (func) {
                "toast" -> toast(arg)
            }
        }

        private fun toast(arg: JSONObject) {
            val message = arg.getString("message")
            Toast.makeText(this@WebActivity, message, Toast.LENGTH_SHORT).show()
        }
    }
}
